package ZmmMoneyLog

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/tiger1103/gfast/v3/api/v1/zmm"
	sysservice "github.com/tiger1103/gfast/v3/internal/app/system/service"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/dao"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/model/do"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/model/entity/association"
	"github.com/tiger1103/gfast/v3/internal/app/zmm/service"
)

func init() {
	service.RegisterZmmMoneyLogShop(NewShop())
}

func NewShop() *sZmmMoneyLogShop {
	return &sZmmMoneyLogShop{}
}

type sZmmMoneyLogShop struct {
}

func (s *sZmmMoneyLogShop) GetList(ctx context.Context, req *zmm.ZmmMoneyLogShopListReq) (total interface{}, list []*association.ZmmMoneyLogShop, err error) {
	where := g.Map{}
	if req.ShopId != "" && req.ShopId != "0" {
		where["shop_id"] = req.ShopId
	}
	if req.StartTime != "" {
		where["recharge_time >= ?"] = req.StartTime
	}
	if req.EndTime != "" {
		where["recharge_time <= ?"] = req.EndTime
	}
	if req.TypeData != "" {
		where["type_data"] = req.TypeData
	}

	m := g.Model(association.ZmmMoneyLogShop{})
	cm := m.Clone()

	total, err = cm.WithAll().Where(where).Count()

	err = m.WithAll().Where(where).OrderDesc("id").Page(req.PageNum, req.PageSize).FieldsEx("deleted_at").Scan(&list)
	if err != nil {
		return
	}

	return
}

func (s *sZmmMoneyLogShop) SaveShopLog(ctx context.Context, logEntity *do.ZmmMoneyLogShop) error {
	userInfo := sysservice.Context().GetLoginUser(ctx)
	if userInfo == nil {
		return nil
	}

	_, err := dao.ZmmMoneyLogShop.Ctx(ctx).Insert(do.ZmmMoneyLogShop{
		ShopId:      logEntity.ShopId,
		BaseShopId:  logEntity.BaseShopId,
		Money:       logEntity.Money,
		CreatedTime: gtime.Now(),
		AdminId:     userInfo.Id,
		MemberId:    logEntity.MemberId,
		OrderId:     logEntity.OrderId,
		TypeData:    logEntity.TypeData,
		Remark:      logEntity.Remark,
	})
	return err
}
